package cn.touna.jss.modules.credit.service.impl;

import cn.touna.jss.common.properties.config.SysConfigProperties;
import cn.touna.risk.api.enums.IntfTypeEnum;
import cn.touna.risk.api.utils.JSONUtil;
import cn.touna.jss.common.entity.CreditQueryRequest;
import cn.touna.jss.common.factory.ResponseFactory;
import cn.touna.jss.common.util.DateUtils;
import cn.touna.jss.modules.credit.mapper.AuthHistoryEntityMapper;
import cn.touna.jss.modules.credit.service.AuthHistoryService;
import cn.touna.jss.modules.custom.auth.entity.AuthHistoryEntity;
import cn.touna.jss.modules.third.gxb.entity.GxbDataRequest;
import cn.touna.risk.api.domain.Response;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 授权认证记录
 * Created by Steve.Tao on 2017/11/1.
 */
@Service
public class AuthHistoryServiceImpl implements AuthHistoryService {

    private static final Logger logger = LogManager.getLogger(AuthHistoryServiceImpl.class);

    @Autowired
    private SysConfigProperties config;

    @Autowired
    private AuthHistoryEntityMapper authHistoryEntityMapper;

    /**
     * 保存授信认证历史
     *
     * @param request
     * @param response
     */
    public void saveAuthHistory(CreditQueryRequest request, Response response) {
        try {
            //聚信立
            if (IntfTypeEnum.JXL_JXLAuth_DATA.equals(request.getMethod())) {
                try {
                    if (response.checkIfFail() || response.getData() == null) {
                        save(request, "聚信立认证", false, response.getMsg());
                    } else {
                        JSONObject obj = getData(response);
                        boolean adopt = 10008 == obj.getInteger("process_code");
                        save(request, "聚信立认证", adopt, response.getMsg());
                    }
                } catch (Exception e) {
                    logger.error("【保存授权认证】保存聚信立出现异常，data:" + response.getData(), e);
                }
                return;
            }

            // 实名认证
            // （众安实名认证，或天行实名认证）
            if (IntfTypeEnum.AUTH_REPORT_DATA.equals(request.getMethod())) {
                try {
                    if (response.checkIfFail() || response.getData() == null) {
                        save(request, "实名认证", false, response.getMsg());
                    } else {
                        JSONObject obj = getData(response);
                        String compareStatus = obj.getString("compareStatus");
                        boolean adopt = "SAME".equals(compareStatus);
                        save(request, "实名认证", adopt, response.getMsg());
                    }
                } catch (Exception e) {
                    logger.error("【保存授权认证】保存实名认证出现异常，data:" + response.getData(), e);
                }
                return;
            }

            //人脸识别
            if (IntfTypeEnum.AUTH_FACE_VERIFY.equals(request.getMethod())) {
                try {
                    if (response.checkIfFail() || response.getData() == null) {
                        save(request, "人脸识别认证", false, response.getMsg());
                    } else {
                        JSONObject obj = getData(response);
                        double verify_score = Double.valueOf(obj.getString("verify_score"));
                        boolean adopt = verify_score > Double.valueOf(config.getVerifyScore());
                        save(request, "人脸识别认证", adopt, response.getMsg());

                    }
                } catch (Exception e) {
                    logger.error("【保存授权认证】保存人脸识别出现异常，data:" + response.getData(), e);
                }
                return;
            }

            //公积金认证
            if(IntfTypeEnum.MOXIE_FUND_BILL.getCode().equals(request.getMethod())){
                try{
                    //无法判断认证失败的情况
                    save(request, "公积金认证", true, "");
                }catch (Exception e){
                    logger.error("【保存授权认证】保存魔蝎公积金出现异常，data:" + response.getData(), e);
                }
            }

            //社保认证
            if(IntfTypeEnum.MOXIE_SECURITY_BILL.getCode().equals(request.getMethod())){
                try{
                    //无法判断认证失败的情况
                    save(request, "社保认证", true, "");
                }catch (Exception e){
                    logger.error("【保存授权认证】保存魔蝎社保出现异常，data:" + response.getData(), e);
                }
            }

            //邮箱认证
            if(IntfTypeEnum.MOXIE_MAIL_BILL.getCode().equals(request.getMethod())){
                try{
                    //无法判断认证失败的情况
                    save(request, "信用卡邮箱认证", true, "");
                }catch (Exception e){
                    logger.error("【保存授权认证】保存魔蝎社保出现异常，data:" + response.getData(), e);
                }
            }
            //淘宝认证
            if("taobao.shujumohe".equals(request.getMethod())){
                try{
                    if(response.getCode().equals("200")){
                        JSONObject jsonObject = (JSONObject)response.getData();
                        String  idCard = jsonObject.getJSONObject("data").getString("identity_code");
                        String  mobile =  jsonObject.getJSONObject("data").getString("user_mobile");
                        request.setMobile(mobile);
                        request.setIdCard(idCard);
                        //无法判断认证失败的情况
                        save(request, "淘宝认证", true, "");
                    }else{
                        save(request, "淘宝认证", false, "");
                    }
                }catch (Exception e){
                    logger.error("【保存授权认证】保存淘宝认证出现异常，data:" + response.getData(), e);
                }
            }


            //工信宝
            if("gongxinbao.getRawdata".equals(request.getMethod())){
                try{
                    if(response.checkIfSuccess()){
                        JSONObject data = (JSONObject) response.getData();
                        String authItem = null;
                        try{
                            if(JSONPath.contains(data,"$.data.authInfoVo.authItem")){
                                authItem = (String)JSONPath.eval(data,"$.data.authInfoVo.authItem");
                            }
                        }catch (Exception e){
                            logger.error(e.getMessage(),e);
                        }
                        if(StringUtils.isEmpty(authItem)){
                            GxbDataRequest req = JSONUtil.jsonToObject(request.getParams(),GxbDataRequest.class) ;
                            authItem = req.getAuthItem();
                        }

                        //电商
                        if("ecommerce".equals(authItem)){
                            save(request,"支付宝认证",true,"");
                        }else if("wechat".equals(authItem)){
                            save(request,"微信认证",true,"");
                        }
                    }
                }catch (Exception e){
                    logger.error("【保存授权认证】保存电商/微信出现异常，data:" + response.getData(), e);
                }
            }

        } catch (Exception e) {
        }
    }

    public void save(CreditQueryRequest request, String label, boolean adopt, String unadoptedMsg) {
        AuthHistoryEntity entity = new AuthHistoryEntity();
        entity.setAuthLabel(label);
        entity.setIdNo(request.getIdCard() != null ? request.getIdCard() : "");
        entity.setMobile(request.getMobile() != null ? request.getMobile() : "");
        entity.setCrNo(request.getCrNo());
        entity.setAdopt(adopt ? 1 : 0);
        entity.setUnadoptedMsg(unadoptedMsg == null ? "" : unadoptedMsg);
        String name = "";
        if (request.getParams() != null)
            name = request.getParams().getString("name");
        if (name == null) name = "";
        entity.setName(name);
        authHistoryEntityMapper.insert(entity);
        logger.info("【保存授权认证成功】 , params{}",entity);
    }


    public List<AuthHistoryEntity> getJxlAuthHistory(String idCard, String mobile) {
        Map<String, String> map = new HashMap<>();
//        map.put("mobile", mobile);
//        map.put("idCard", idCard);
        AuthHistoryEntity  authHistoryEntity = new  AuthHistoryEntity();
        authHistoryEntity.setMobile(mobile);
        authHistoryEntity.setIdCard(idCard);
        authHistoryEntity.setDateCreated(DateUtils.addDay(new Date(),-30));
        List<AuthHistoryEntity> list = authHistoryEntityMapper.jxlAuthList(authHistoryEntity);
        return list;
    }

    public Response getAuthHistory(String idCard, String mobile) {
        List<AuthHistoryEntity> list = authHistoryEntityMapper.selectList(idCard, mobile);
        StringBuilder sb = new StringBuilder();
        for (AuthHistoryEntity entity : list) {
            if (sb.indexOf(entity.getAuthLabel()) == -1) {
                sb.append(entity.getAuthLabel());
                if (entity.getAdopt() == 1) {
                    sb.append("成功");
                } else {
                    sb.append("失败");
                }
                sb.append(",");
            }
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return ResponseFactory.success(sb.toString());
    }

    private JSONObject getData(Response response) {
        if (response.getData() instanceof String) {
            return JSONObject.parseObject((String) response.getData());
        }
        if (response.getData() instanceof JSONObject)
            return (JSONObject) response.getData();
        return (JSONObject) JSONObject.toJSON(response.getData());
    }
}
